package com.sunwhite.herostore;

import com.sunwhite.herostore.cmdhandler.CmdHandlerFactory;
import com.sunwhite.herostore.common.GameMsgRecognizer;
import com.sunwhite.herostore.common.MySqlSessionFacoty;
import com.sunwhite.herostore.config.RedisUtil;
import com.sunwhite.herostore.config.mq.MQConsumer;
import com.sunwhite.herostore.config.mq.MQProducer;
import com.sunwhite.herostore.handler.GameMsgHandler;
import com.sunwhite.herostore.msg.util.GameMsgEncode;
import com.sunwhite.herostore.msg.util.GameMsgDecode;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * netty主服务启动类
 */
public class ServerMain {
    public static void main(String[] args) {
        //Factoryc初始化
        CmdHandlerFactory.init();
        GameMsgRecognizer.init();
        MySqlSessionFacoty.init();
        RedisUtil.init();
        MQProducer.init();

        EventLoopGroup bossGroup = new NioEventLoopGroup();     // 接受客户端请求线城池
        EventLoopGroup workerGroup = new NioEventLoopGroup();   //客户端请求处理类

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);  //服务器通道的处理方式
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>(){   //客户端通道的处理器方式
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(
                        new HttpServerCodec(), //http服务编解码器
                        new HttpObjectAggregator(65535),//http内容长度限制
                        new WebSocketServerProtocolHandler("/websocket"),//websocket 协议处理器 在这里处理握手 ping pong 等消息
                        new GameMsgDecode(),//加入自定义消息编码器
                        new GameMsgEncode(),//加入自定义消息解码器
                        new GameMsgHandler()    //加入自定义消息处理器
                );
            }
        });

        try {
            ChannelFuture channelFuture = serverBootstrap.bind(12345).sync();
            if (channelFuture.isSuccess()){
                System.out.println("服务器启动成功！");
            }
            //等待服务器信道关闭
            //也就是不要关闭服务器可以让服务器一直提供服务
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
